<?php

namespace app\models;

use yii\db\ActiveRecord;
use Yii;

class User extends ActiveRecord{
	public static function tableName(){
		return "{{%user}}";
	}

	public function rules(){
		return [
			 ['openid', 'required', 'message' => '', 'on' => ['insertNuPa','updateNuPa','updateState']],
			 ['number', 'required', 'message' => '', 'on' => ['insertNuPa','updateNuPa']],
			 ['password', 'required', 'message' => '', 'on' => ['insertNuPa','updateNuPa']],
		];
	}	

	public function getNuPaByOpenId($openid){
		$data = self::find()->select(['openid','number','password'])->where('openid = :openid',[':openid'=>$openid])->asArray()->one();
		return $data;
	}

	public function judgeByOpenId($openid){
		$data = self::find()->where('openid = :openid and state = :state',[':openid'=>$openid,':state'=>'1'])->asArray()->one();
		if($data){
			return true;
		}
		return false;
	}

	public function insertNuPa($data){
             date_default_timezone_set('PRC');
             $createtime = date('Y-m-d H:i:s');
             $this->createTime = $createtime;
             $this->openid = $data['openId'];
             $this->number = $data['number'];
             $identity = $data['number']/10000000000;
             $this->identity = $identity;
             $this->password = $data['password'];
             $this->nickname = $data['nickname'];
             $this->avatarUrl = $data['avatarUrl'];
             $result = $this->save();
             if($result){
                 $error = 0;
                 return $error;
              }else{
                 $error = $this->getErrors();
                 return $error;
            }
	}
	
	public function updateNuPa($data){
           //date_default_timezone_set('PRC');
           //$createtime = date('Y-m-d H:i:s');
           //$this->createTime = $createtime;
             $openid = $data['openId'];
             $number = $data['number'];
             $password = $data['password'];
             $nickname = $data['nickname'];
             $avatarUrl = $data['avatarUrl'];
             $this->updateAll(['number' => $number,'password' => $password,'nickname' => $nickname,'avatarUrl' => $avatarUrl,'state' => 1],'openid = :openid',[':openid' => $openid]);
             $result=$this->save();    
             if($result){
                   $error = 0;
                   return $error;
          }  else{
                   $error = $this->getErrors();
                   return $error;
            }    

        //     (bool)$this->updateAll(['number'=>$this->number,'password'=>$this->password],'openid = :openid and state = :state',[':openid'=>$this->openid,':state'=>'1']);
       }			

	public function updateState($data){
		$this->scenario = 'updateState';
		if($this->load($data,'') && $this->validate()){
			return (bool)$this->updateAll(['state'=>'0'],'openid = :openid and state = :state',[':openid'=>$this->openid,':state'=>'1']);
		}
		return false;
	}
}
